from flask import Flask, request

from extract.extractor import Extractor
from src.application.server_api import middleware
from src.application.tikTok import TikTok
from src.config.parameter import Parameter
from src.custom.response import Response
from src.handle.account import Account
from src.handle.link import Link
from src.handle.live import Live, generate_live_params
from src.handle.search import Search
from src.handle.user import User


class ServerApi:
    def __init__(self, parameter: "Parameter"):
        self.parameter = parameter
        self.extractor = Extractor(parameter)

    def run_server(self):
        app = Flask(__name__)

        @app.route('/', methods=['GET'])
        @middleware.not_cookie_middleware(self.parameter)
        def index():
            return Response.success(None, "欢迎使用")

        # 获取视频
        @app.route('/get-video', methods=['POST'])
        @middleware.check_cookie_middleware(self.parameter)
        def get_video():
            u = request.json.get('url')
            if not u:
                return Response.fail(500, "请输入链接")
            # u = 'https://v.douyin.com/iYfuYmMb/'
            link_instance = Link(self.parameter)
            _, ids = link_instance.works(u)

            if not ids:
                print(m := f"{u} 提取作品 ID 失败")
                return {"data": None, "message": m}
            result = TikTok(self.parameter).input_links_acquisition(False, ids)
            return Response.success(result)

        # 搜索
        @app.route('/search', methods=['POST'])
        @middleware.check_cookie_middleware(self.parameter)
        def search():
            keyword = request.json.get("keyword")
            _type = request.json.get("type", "1")
            pages = request.json.get("pages", "1")
            sort_type = request.json.get("sort_type", "0")
            publish_time = request.json.get("publish_time", "0")
            if not keyword:
                return Response.fail(500, "请输入关键词")
            search = Search(self.parameter)
            params = search.enter_search_criteria(keyword=keyword, _type=_type, pages=pages, sort_type=sort_type, publish_time=publish_time)
            return Response.success(search.run(*params))

        # 账号信息获取
        @app.route('/user-info', methods=['POST'])
        @middleware.check_cookie_middleware(self.parameter)
        def user_info():
            sec_user_ids = Link(self.parameter).user(u := request.json.get("url"))
            if not sec_user_ids:
                return Response.fail(500, f"{u} 提取账号 sec_user_id 失败")
            users = [User(self.parameter, i).run() for i in sec_user_ids]
            return Response.success(users)

        # 账号作品获取
        @app.route('/account-list', methods=['POST'])
        @middleware.check_cookie_middleware(self.parameter)
        def account_list():
            sec_user_ids = Link(self.parameter).user(u := request.json.get("url"))
            # post 作品 favorite 作者喜欢的列表
            tab = request.json.get('tab', 'post')
            max_cursor = int(request.json.get("max_cursor", 0))
            if not sec_user_ids:
                return Response.fail(500, f"{u} 提取账号 sec_user_id 失败")
            result = Account(self.parameter,
                sec_user_id=sec_user_ids[0], tab=tab, max_cursor=max_cursor).run()
            return Response.success(result)

        # 直播获取
        @app.route('/get-live', methods=['POST'])
        @middleware.check_cookie_middleware(self.parameter)
        def get_live():
            params = generate_live_params(*Link(self.parameter).live(u := request.json.get("url")))
            if not params:
                m = f"{u} 提取直播 ID 失败"
                print(m)
                return Response.fail(500, m)
            live_data = [
                Live(
                    self.parameter,
                    **i,
                ).run() for i in params]
            if not any(live_data):
                m = "获取直播数据失败"
                print(m)
                return {"data": None, "message": m}
            return Response.success(live_data)

        # 直播录制
        @app.route('/live-interactive', methods=['POST'])
        @middleware.check_cookie_middleware(self.parameter)
        def get_live_interactive():
            params = generate_live_params(*Link(self.parameter).live(u := request.json.get("url")))
            if not params:
                m = f"{u} 提取直播 ID 失败"
                print(m)
                return Response.fail(500, m)
            choice = int(request.json.get("choice", 1))
            live_data = Live(self.parameter).live_interactive(params, choice)
            # if not any(live_data):
            #     m = "获取直播数据失败"
            #     print(m)
            #     return {"data": None, "message": m}
            return Response.success({"process": live_data})

        # 直播录制停止
        @app.route('/live-interactive-stop', methods=['POST'])
        @middleware.not_cookie_middleware(self.parameter)
        def stop_live_interactive():
            processIds = request.json.get('process_ids', [])
            return Response.success({"process": Live(self.parameter).stop_live_interactive(processIds)})

        return app
